package com.luck.easyfoodbatch.ui;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.luck.easyfoodbatch.App;
import com.luck.easyfoodbatch.R;
import com.luck.easyfoodbatch.adapter.ClassListAdapter;
import com.luck.easyfoodbatch.adapter.GridImageAdapter2;
import com.luck.easyfoodbatch.adapter.UploadDiscountAdapter;
import com.luck.easyfoodbatch.dialog.CustomDialog;
import com.luck.easyfoodbatch.entity.Discount;
import com.luck.easyfoodbatch.entity.User;
import com.luck.easyfoodbatch.mvp.home.ClassListsModel;
import com.luck.easyfoodbatch.mvp.home.ClassListsPresenter;
import com.luck.easyfoodbatch.mvp.home.ClassListsView;
import com.luck.easyfoodbatch.mvp.mine.EditBasicInfoModel;
import com.luck.easyfoodbatch.mvp.mine.EditBasicInfoPresenter;
import com.luck.easyfoodbatch.mvp.mine.EditBasicInfoView;
import com.luck.easyfoodbatch.mvp.mine.GetBasicInfoModel;
import com.luck.easyfoodbatch.mvp.mine.GetBasicInfoPresenter;
import com.luck.easyfoodbatch.mvp.mine.GetBasicInfoView;
import com.luck.easyfoodbatch.mvp.mine.MyAddressModel;
import com.luck.easyfoodbatch.mvp.mine.MyAddressPresenter;
import com.luck.easyfoodbatch.mvp.mine.MyAddressView;
import com.luck.easyfoodbatch.mvp.mine.PublicGoods1Model;
import com.luck.easyfoodbatch.mvp.mine.PublicGoods1Presenter;
import com.luck.easyfoodbatch.mvp.mine.PublicGoods1View;
import com.luck.easyfoodbatch.mvp.mine.ShoperDelImgView;
import com.luck.easyfoodbatch.mvp.mine.ShoperInfoModel;
import com.luck.easyfoodbatch.mvp.mine.ShoperInfoPresenter;
import com.luck.easyfoodbatch.mvp.mine.ShoperInfoView;
import com.luck.easyfoodbatch.mvp.mine.UploadImageModel;
import com.luck.easyfoodbatch.mvp.mine.UploadImageView;
import com.luck.easyfoodbatch.mvp.mine.UploadSinglePresenter;
import com.luck.easyfoodbatch.mvp.model.Address;
import com.luck.easyfoodbatch.mvp.model.ClassModel;
import com.luck.easyfoodbatch.mvp.model.Collect;
import com.luck.easyfoodbatch.mvp.model.GetBasic;
import com.luck.easyfoodbatch.mvp.model.Goods1Model;
import com.luck.easyfoodbatch.mvp.model.MyAddress;
import com.luck.easyfoodbatch.mvp.model.ShoperModel;
import com.luck.easyfoodbatch.mvp.model.UploadModel;
import com.luck.easyfoodbatch.util.HttpUtil;
import com.luck.easyfoodbatch.util.SharedPreferencesUtil;
import com.luck.easyfoodbatch.util.T;
import com.luck.easyfoodbatch.util.Tools;
import com.luck.easyfoodbatch.util.Utils;
import com.luck.easyrecyclerview.decoration.RecycleViewDivider;
import com.luck.easyrecyclerview.swipe.MyLayoutManager;
import com.luck.picture.lib.model.FunctionConfig;
import com.luck.picture.lib.model.PictureConfig;
import com.yalantis.ucrop.entity.LocalMedia;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class UploadShopInfoActivity extends BaseActivity implements ShoperInfoView, RadioGroup.OnCheckedChangeListener, ShoperDelImgView, UploadImageView, PublicGoods1View, MyAddressView, ClassListsView, GetBasicInfoView, EditBasicInfoView {

    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;
    @BindView(R.id.recyclerView)
    RecyclerView discount;
    @BindView(R.id.rl_address)
    RelativeLayout rlAddress;
    @BindView(R.id.ll_address)
    LinearLayout llAddress;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_phone)
    TextView tvPhone;
    @BindView(R.id.tv_add_discount)
    TextView tv_add_discount;
    @BindView(R.id.tv_address_details)
    TextView tvAddressDetails;
    @BindView(R.id.scrollView)
    ScrollView scrollView;
    @BindView(R.id.btn_exchange)
    Button btn_exchange;
    @BindView(R.id.et_shop_number)
    EditText etShopNumber;
    @BindView(R.id.et_shop_name)
    EditText etShopName;
    @BindView(R.id.et_starting)
    EditText etStarting;
    @BindView(R.id.et_retail_price)
    EditText etRetailPrice;
    @BindView(R.id.rb_free)
    RadioButton rbFree;
    @BindView(R.id.rb_without)
    RadioButton rbWithout;
    @BindView(R.id.rgbs)
    RadioGroup rgbs;
    @BindView(R.id.tv_transport_line)
    TextView tvTransportLine;
    @BindView(R.id.rb_transport1)
    RadioButton rbTransport1;
    @BindView(R.id.rb_transport2)
    RadioButton rbTransport2;
    @BindView(R.id.rgb_transport)
    RadioGroup rgbTransport;
    @BindView(R.id.ll_transport)
    LinearLayout llTransport;
    @BindView(R.id.et_mail)
    EditText et_mail;
    @BindView(R.id.ll_classification)
    LinearLayout ll_classification;
    @BindView(R.id.tv_classification)
    TextView tv_classification;
    @BindView(R.id.ll_city)
    LinearLayout ll_city;
    @BindView(R.id.tv_field)
    TextView tv_field;
    @BindView(R.id.tv_free_post_num)
    TextView tv_free_post_num;
    @BindView(R.id.ll_free_post_num)
    LinearLayout ll_free_post_num;
    @BindView(R.id.et_number)
    EditText et_number;
    @BindView(R.id.et_discount)
    EditText et_discount;
    @BindView(R.id.tv_unit)
    TextView tv_unit;
    @BindView(R.id.et_kg)
    EditText et_kg;
    @BindView(R.id.et_volume)
    EditText et_volume;
    @BindView(R.id.et_singe_num)
    EditText et_singe_num;
    @BindView(R.id.et_single_unit)
    EditText et_single_unit;
    private GridImageAdapter2 adapter;
    private List<GetBasic.DataBean.ThumbsBean> thumbs = new ArrayList<>();
    private List<LocalMedia> photoInfos = new ArrayList<>();
    private List<Discount> discounts = new ArrayList<>();
    private UploadDiscountAdapter discountAdapter;
    protected static final int REQUEST_STORAGE_READ_ACCESS_PERMISSION = 101;
    private Handler handler = new Handler();
    private String class_id = "", country_id = "", warehouse_id = "", use_ydx = "2";
    private Gson gson;
    private int selectPosition = 0;// 选择的下标
    private String is_free_post = "1";//是否包邮 1不包2包 (不包要传use_ydx，包传free_post_num)
    private UploadImageModel imageModel;
    private List<File> files = new ArrayList<>();
    private List<String> imgs = new ArrayList<>();
    private PublicGoods1Model goods1Model;
    private List<MyAddress.DataBean> list = new ArrayList<>();
    private List<ClassModel.DataBean.ImportBean> classList = new ArrayList<>();
    private List<ClassModel.DataBean.ImportBean> gc = new ArrayList<>();
    private List<ClassModel.DataBean.ImportBean> jk = new ArrayList<>();
    private MyAddressModel addressModel;
    private ClassModel.DataBean data;
    private ClassListsModel listsModel;
    private int type = 0;
    private int data_type = 0;// 0是国产 1是进口
    private String title = "", gid = "";
    private GetBasicInfoModel infoModel;
    private EditBasicInfoModel editBasicInfoModel;
    private int showType = 0;
    private ShoperInfoModel shoperInfoModel;
    private int product_type = 1;//产品类型1国产2进口
    private String p_id = "";
    private boolean isLoading = false;// 为true是第一次进来加载，不弹框
    private boolean isupload = false;// 编辑时 是否更新过图片
    protected static final int REQUEST_STORAGE_READ_ACCESS_CAMERA = 102;
    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals("action.app.refresh.address")) {
                // 删除没一个地址了
                rlAddress.setVisibility(View.VISIBLE);
                llAddress.setVisibility(View.GONE);
                tvName.setText("");
                tvPhone.setText("");
                warehouse_id = "";
                tvAddressDetails.setText("");
            } else if (intent.getAction().equals("action.app.refresh.default")) {
                // 设置为默认地址 时回调这里
                Address.DataBean bean = (Address.DataBean) intent.getSerializableExtra("bean");
                rlAddress.setVisibility(View.GONE);
                llAddress.setVisibility(View.VISIBLE);
                tvName.setText("负责人：" + bean.getUname());
                tvPhone.setText(bean.getMobile());
                String street = bean.getStreet();
                warehouse_id = bean.getAddress_id() + "";
                tvAddressDetails.setText("仓库地址：" + bean.getAddress_str());
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        type = getIntent().getIntExtra("type", 0);
        if (type == 1) {
            // 修改商品信息
            title = "修改商品(基本信息)";
        } else {
            title = "上传商品(基本信息)";

        }
        setContentView(R.layout.activity_upload_shop_info, title, MODE_BACK_NAVIGATION);
        ButterKnife.bind(this);
        p_id = (String) SharedPreferencesUtil.getData(UploadShopInfoActivity.this, HttpUtil.P_ID, "3");
        shoperInfoModel = new ShoperInfoPresenter(this, mContext);
        shoperInfoModel.shoperInfo(1);
        registerReceiver(receiver, "action.app.refresh.address", "action.app.refresh.default");
        gid = getIntent().getStringExtra("gid");
        gson = new Gson();
        if (type == 1) {
            // 获取商品基本信息
            btn_exchange.setText("保存");
            showProgressDialog(getString(R.string.app_loading));
            infoModel = new GetBasicInfoPresenter(this, mContext);
            infoModel.requestBasic(gid, p_id);
        } else {
            btn_exchange.setText("下一步");
        }
        listsModel = new ClassListsPresenter(this, mContext);
        addressModel = new MyAddressPresenter(this, mContext);
        addressModel.getMyAddressList("2");
        listsModel.getClassList(1, 0, "");
        isLoading = true;
        rgbs.setOnCheckedChangeListener(this);
        rgbTransport.setOnCheckedChangeListener(this);
        adapter = new GridImageAdapter2(mContext, onAddPicClickListener);
        LinearLayoutManager mLayoutManager = new LinearLayoutManager(this);
        mLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.setAdapter(adapter);
        adapter.setOnItemClickListener(new GridImageAdapter2.OnItemClickListener() {
            @Override
            public void onItemClick(int position, View v) {

            }
        });
        imageModel = new UploadSinglePresenter(UploadShopInfoActivity.this, mContext);
        // 折扣
        MyLayoutManager manager = new MyLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        discount.addItemDecoration(new RecycleViewDivider(
                mContext, LinearLayoutManager.HORIZONTAL, Utils.dip2px(mContext, 0.5F), getResources().getColor(R.color.line_color)));
        discount.setLayoutManager(manager);
        discountAdapter = new UploadDiscountAdapter(this);
        discount.setAdapter(discountAdapter);
        if (ContextCompat.checkSelfPermission(UploadShopInfoActivity.this, Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED) {
            requestPermission(Manifest.permission.CAMERA,
                    getString(R.string.mis_permission_camera),
                    REQUEST_STORAGE_READ_ACCESS_CAMERA);
        }
    }

    private GridImageAdapter2.onAddPicClickListener onAddPicClickListener = new GridImageAdapter2.onAddPicClickListener() {
        @Override
        public void onAddPicClick(int type, int position) {
            switch (type) {
                case 0:
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN // Permission was added in API Level 16
                            && ActivityCompat.checkSelfPermission(UploadShopInfoActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE)
                            != PackageManager.PERMISSION_GRANTED) {
                        requestPermission(Manifest.permission.READ_EXTERNAL_STORAGE,
                                getString(R.string.mis_permission_rationale),
                                REQUEST_STORAGE_READ_ACCESS_PERMISSION);
                    } else {
                        int size = 5 - photoInfos.size();
                        if (size == 0) {
                            size = 5;
                        }
                        FunctionConfig options = new FunctionConfig();
                        options.setCompress(true);
                        options.setMaxSelectNum(size);
                        PictureConfig.init(options);
                        PictureConfig.getPictureConfig().openPhoto(UploadShopInfoActivity.this, resultCallback);
                    }
                    break;
                case 1:
                    if (photoInfos.size() > 0) {
                        photoInfos.remove(position);
                    }
                    adapter.notifyItemRemoved(position);
                    adapter.notifyDataSetChanged();
                    break;
            }
        }
    };

    private void requestPermission(final String permission, String rationale, final int requestCode) {
        if (ActivityCompat.shouldShowRequestPermissionRationale(this, permission)) {
            new AlertDialog.Builder(this)
                    .setTitle("获取相册权限")
                    .setMessage(rationale)
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            ActivityCompat.requestPermissions(UploadShopInfoActivity.this, new String[]{permission}, requestCode);
                        }
                    })
                    .setNegativeButton("取消", null)
                    .create().show();
        } else {
            ActivityCompat.requestPermissions(this, new String[]{permission}, requestCode);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == REQUEST_STORAGE_READ_ACCESS_PERMISSION) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                int size = 5 - photoInfos.size();
                if (size == 0) {
                    size = 5;
                }
                FunctionConfig options = new FunctionConfig();
                options.setCompress(true);
                options.setMaxSelectNum(size);
                PictureConfig.init(options);
                PictureConfig.getPictureConfig().openPhoto(UploadShopInfoActivity.this, resultCallback);
            }
        } else if (requestCode == REQUEST_STORAGE_READ_ACCESS_CAMERA) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {

            }
        } else {
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }


    private String no = "";
    private String goods_name = "";
    private String field = "";
    private String classification = "";
    private String starting = "";
    private String retailprice = "";
    private String packetmail = "";
    private String number = "";
    private String diss = "";
    private String unit = "";
    private String kg = "";
    private String volume = "";

    @OnClick({R.id.rl_address, R.id.ll_address, R.id.tv_add_discount, R.id.btn_exchange, R.id.ll_classification, R.id.ll_city})
    public void onClick(View v) {
        Intent intent = new Intent();
        Bundle bundle = new Bundle();
        switch (v.getId()) {
            case R.id.ll_address:
                bundle.putInt("type", 2);
                bundle.putInt("address_type", 2);
                intent.setClass(mContext, AddressManagementActivity.class);
                intent.putExtras(bundle);
                startActivityForResult(intent, 200);
                break;
            case R.id.rl_address:
                bundle.putInt("type", 2);
                bundle.putInt("address_type", 2);
                intent.setClass(mContext, AddressManagementActivity.class);
                intent.putExtras(bundle);
                startActivityForResult(intent, 200);
                break;
            case R.id.tv_add_discount:
                if (discounts.size() < 5) {
                    Discount dis = new Discount();
                    dis.setCount("");
                    dis.setDiscount("");
                    discounts.add(dis);
                    for (int i = 0; i < discount.getChildCount(); i++) {
                        LinearLayout layout = (LinearLayout) discount.getChildAt(i);// 获得子item的layout
                        EditText et_number = (EditText) layout.findViewById(R.id.et_number);
                        EditText et_discount = (EditText) layout.findViewById(R.id.et_discount);
                        discounts.get(i).setCount(et_number.getText().toString().trim());
                        discounts.get(i).setDiscount(et_discount.getText().toString().trim());
                    }
                    discountAdapter.setList(discounts);
                    discountAdapter.notifyDataSetChanged();
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            scrollView.fullScroll(ScrollView.FOCUS_DOWN);
                        }
                    });
                } else {
                    T.showToast(mContext, "最多添加5个折扣~");
                }
                break;
            case R.id.btn_exchange:

                no = etShopNumber.getText().toString().trim();
                goods_name = etShopName.getText().toString().trim();
                field = tv_field.getText().toString().trim();
                classification = tv_classification.getText().toString().trim();
                starting = etStarting.getText().toString().trim();
                retailprice = etRetailPrice.getText().toString().trim();
                packetmail = et_mail.getText().toString().trim();
                number = et_number.getText().toString().trim();
                diss = et_discount.getText().toString().trim();
                unit = tv_unit.getText().toString().trim();
                kg = et_kg.getText().toString().trim();
                volume = et_volume.getText().toString().trim();
                imgs.clear();
                for (LocalMedia p : photoInfos) {
                    int lastIndexOf1 = 0;
                    String photoPath = p.getPath();
                    if (photoPath.startsWith("http")) {
                        lastIndexOf1 = photoPath.lastIndexOf("screen") - 1;
                        if (lastIndexOf1 != -2) {
                            photoPath = photoPath.substring(lastIndexOf1, photoPath.length());
                        } else {
                            lastIndexOf1 = photoPath.lastIndexOf("/") - 1;
                            photoPath = photoPath.substring(lastIndexOf1, photoPath.length());
                        }
                    }

                    imgs.add(photoPath);
                }

                if (Tools.isNull(warehouse_id)) {
                    T.showToast(mContext, "请选择仓库地址");
                } else if (imgs.size() == 0) {
                    T.showToast(mContext, "请上传商品图片");
                } else if (Tools.isNull(no)) {
                    T.showToast(mContext, "请输入商品货号");
                } else if (Tools.isNull(goods_name)) {
                    T.showToast(mContext, "请输入商品名称");
                } else if (Tools.isNull(field)) {
                    T.showToast(mContext, "请选择商品产地");
                } else if (Tools.isNull(classification)) {
                    T.showToast(mContext, "请选择商品分类");
                } else if (Tools.isNull(starting)) {
                    T.showToast(mContext, "请输入起批量");
                } else if (Tools.isNull(retailprice)) {
                    T.showToast(mContext, "请输入单品零售原价");
                } else if (Tools.isNull(packetmail) && !rbWithout.isChecked()) {
                    T.showToast(mContext, "请输入多少起包邮");
                } else if (Tools.isNull(number)) {
                    T.showToast(mContext, "请输入数量");
                } else if (Tools.isNull(diss)) {
                    T.showToast(mContext, "请输入单位");
                } else if (Tools.isNull(unit)) {
                    T.showToast(mContext, "请输入商品包装");
                } else if (Tools.isNull(kg)) {
                    T.showToast(mContext, "请输入包装重量");
                } else if (Tools.isNull(volume)) {
                    T.showToast(mContext, "请输入整体包装体积");
                } else {
                    if (rbFree.isChecked()) {
                        // 如果包邮 不传
                        use_ydx = "";
                    } else {
                        // use_ydx = "2";
                    }
                    showType = 1;
                    showProgressDialog("正在加载，请稍候……");
                    files.clear();
                    for (LocalMedia p : photoInfos) {
                        String path = p.getPath();
                        if (!path.startsWith("http")) {
                            // 本地图片
                            if (p.isCompressed()) {
                                files.add(new File(p.getCompressPath()));
                            } else {
                                files.add(new File(p.getPath()));
                            }
                        }
                    }
                    if (files.size() > 0) {
                        imageModel.uploads(1, null, files);
                    } else {
                        showType = 0;
                        String paths = "";
                        String json = toListJson();
                        if (type == 1) {
                            paths = Tools.tempImg(imgs);
                            editBasicInfoModel = new EditBasicInfoPresenter(this, mContext);
                            editBasicInfoModel.requestEditBasicInfo(gid, warehouse_id, paths, no, goods_name, country_id, class_id, starting, retailprice, is_free_post, use_ydx, packetmail, json, number, diss, unit, kg, volume, et_singe_num.getText().toString().trim(), et_single_unit.getText().toString().trim());
                        } else {
                            // 添加基本信息
                            paths = Tools.tempImg(imgs);
                            goods1Model = new PublicGoods1Presenter(this, mContext);
                            goods1Model.uploadGoods(warehouse_id, paths, no, goods_name, country_id, class_id, starting, retailprice, is_free_post, use_ydx, packetmail, json, number, diss, unit, kg, volume, et_singe_num.getText().toString().trim(), et_single_unit.getText().toString().trim());
                        }
                    }
                }
                break;
            case R.id.ll_classification:
                if (Tools.isNull(tv_field)) {
                    T.showToast(mContext, "请先选择商品产地~");
                } else {
                    isLoading = false;
                    showProgressDialog(getString(R.string.app_loading));
                    listsModel.getClassList(1, 0, "");
                }
                break;
            case R.id.ll_city:
                intent.setClass(mContext, SelectionPointActivity.class);
                startActivityForResult(intent, 300);
                break;
        }
    }


    /**
     * 处理商品折扣数据为json
     *
     * @return
     */
    private String toListJson() {
        Discount dis;
        discounts.clear();
        for (int i = 0; i < discount.getChildCount(); i++) {
            dis = new Discount();
            LinearLayout layout = (LinearLayout) discount.getChildAt(i);// 获得子item的layout
            EditText et_number = (EditText) layout.findViewById(R.id.et_number);
            EditText et_discount = (EditText) layout.findViewById(R.id.et_discount);
            dis.setCount(et_number.getText().toString().trim());
            dis.setDiscount(et_discount.getText().toString().trim());
            discounts.add(dis);
        }
        return gson.toJson(discounts);
    }

    private PictureConfig.OnSelectResultCallback resultCallback = new PictureConfig.OnSelectResultCallback() {
        @Override
        public void onSelectSuccess(List<LocalMedia> list) {
            photoInfos.addAll(list);
            adapter.setPhotoInfos(photoInfos);
            adapter.notifyDataSetChanged();
        }
    };

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 200:
                    if (data != null) {
                        MyAddress.DataBean bean = (MyAddress.DataBean) data.getSerializableExtra("bean");
                        if (bean != null) {
                            rlAddress.setVisibility(View.GONE);
                            llAddress.setVisibility(View.VISIBLE);
                            tvName.setText("负责人：" + bean.getUname());
                            tvPhone.setText(bean.getMobile());
                            String street = bean.getStreet();
                            warehouse_id = bean.getAddress_id();
                            tvAddressDetails.setText("仓库地址：" + bean.getAddress_str() + " " + street);
                        }
                    }
                    break;
                case 300:
                    // 选择产地
                    if (data != null) {
                        String name = data.getStringExtra("name");
                        country_id = data.getStringExtra("country_id");
                        tv_field.setText(name);
                        if (!Tools.isNull(country_id) && country_id.equals("1")) {
                            // 如果产地是中国，则为国产 否则是进口
                            data_type = 0;
                        } else if (!Tools.isNull(country_id) && !country_id.equals("1")) {
                            // 进口
                            data_type = 1;
                        } else {
                            T.showToast(mContext, "产地出现未知错误，请重新选择~");
                        }

                        // 如果用户选择了分类，在遍历下 产地是国产还是进口 默默替换
                        if (!Tools.isNull(tv_classification)) {
                            ClassModel.DataBean.ImportBean bean = null;
                            switch (data_type) {
                                case 0:
                                    //国产
                                    bean = gc.get(selectPosition);
                                    class_id = bean.getCid();
                                    Log.i("产品状态---->", "国产id" + class_id + "---" + "国产name" + bean.getName());
                                    break;
                                case 1:
                                    // 进口
                                    bean = jk.get(selectPosition);
                                    class_id = bean.getCid();
                                    Log.i("产品状态---->", "进口id" + class_id + "---" + "进口name" + bean.getName());
                                    break;
                            }
                        }
                    }
                    break;
                case 400:
                    setResult(RESULT_OK);
                    finish();
                    break;
            }
        }
    }

    @Override
    public void onCheckedChanged(RadioGroup radioGroup, int i) {
        switch (i) {
            case R.id.rb_free:
                // 包邮
                tvTransportLine.setVisibility(View.GONE);
                llTransport.setVisibility(View.GONE);
                ll_free_post_num.setVisibility(View.VISIBLE);
                tv_free_post_num.setVisibility(View.VISIBLE);
                is_free_post = "2";
                break;
            case R.id.rb_without:
                // 不包邮
                tvTransportLine.setVisibility(View.VISIBLE);
                llTransport.setVisibility(View.VISIBLE);
                ll_free_post_num.setVisibility(View.GONE);
                tv_free_post_num.setVisibility(View.GONE);
                is_free_post = "1";
                break;
            case R.id.rb_transport1:
                // 使用运东西
                use_ydx = "2";
                break;
            case R.id.rb_transport2:
                // 不使用
                use_ydx = "1";
                break;
        }
    }

    /**
     * 分类框
     *
     * @param
     */
    private void showClassDialog(final List<ClassModel.DataBean.ImportBean> list) {
        final CustomDialog dialog = new CustomDialog(mContext, App.screenWidth * 3 / 4,
                LinearLayout.LayoutParams.WRAP_CONTENT,
                R.layout.wind_class_dialog_xml, R.style.Theme_dialog);
        ListView listview = (ListView) dialog.findViewById(R.id.listview);
        ClassListAdapter adapter = new ClassListAdapter(this, list);
        listview.setAdapter(adapter);
        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                tv_classification.setText(list.get(position).getName());
                class_id = list.get(position).getCid();
                selectPosition = position;
                dialog.dismiss();
            }
        });
        dialog.show();
    }

    @Override
    public void uploadSuccess(UploadModel model) {
        if (model != null) {
            if (model.getStatus() == HttpUtil.RESULT_OK) {
                List<String> data = model.getData();
                if (data == null) {
                    data = new ArrayList<>();
                }
                imgs = data;
                for (LocalMedia p : photoInfos) {
                    int lastIndexOf = 0;
                    String path = p.getPath();
                    if (path.startsWith("http")) {
                        lastIndexOf = path.lastIndexOf("screen") - 1;
                        if (lastIndexOf != -2) {
                            path = path.substring(lastIndexOf, path.length());
                        } else {
                            lastIndexOf = path.lastIndexOf("/") - 1;
                            path = path.substring(lastIndexOf, path.length());
                        }
                        imgs.add(path);
                    }
                }
                isupload = true;
                showType = 0;
                String paths = "";
                String json = toListJson();
                if (type == 1) {
                    paths = Tools.tempImg(imgs);
                    editBasicInfoModel = new EditBasicInfoPresenter(this, mContext);
                    editBasicInfoModel.requestEditBasicInfo(gid, warehouse_id, paths, no, goods_name, country_id, class_id, starting, retailprice, is_free_post, use_ydx, packetmail, json, number, diss, unit, kg, volume, et_singe_num.getText().toString().trim(), et_single_unit.getText().toString().trim());
                } else {
                    // 添加基本信息
                    paths = Tools.tempImg(imgs);
                    goods1Model = new PublicGoods1Presenter(this, mContext);
                    goods1Model.uploadGoods(warehouse_id, paths, no, goods_name, country_id, class_id, starting, retailprice, is_free_post, use_ydx, packetmail, json, number, diss, unit, kg, volume, et_singe_num.getText().toString().trim(), et_single_unit.getText().toString().trim());
                }
            }
        }
    }

    @Override
    public void publicGoods1Success(Goods1Model model) {
        if (model.getStatus() == HttpUtil.RESULT_OK) {
            Intent intent = new Intent();
            Bundle bundle = new Bundle();
            bundle.putString("gid", model.getData().getGid() + "");
            double number = 0;
            if (!Tools.isNull(et_number)) {
                String trim = et_number.getText().toString().trim();
                number = Double.parseDouble(trim);
            }
            int product_type = 1;
            if (!Tools.isNull(country_id)) {
                if (country_id.equals("1")) {
                    // 国产
                    product_type = 1;
                } else {
                    // 进口
                    product_type = 2;
                }
            }
            bundle.putDouble("mail", number);
            bundle.putInt("product_type", product_type);
            intent.setClass(mContext, UploadBatchActivity.class);
            intent.putExtras(bundle);
            startActivityForResult(intent, 400);
        } else {
            T.showToast(mContext, model.getMsg());
        }
    }

    @Override
    public void myAddressSuccess(MyAddress model) {
        if (model != null) {
            if (model.getStatus() == HttpUtil.RESULT_OK) {
                list = model.getData();
                if (list != null && list.size() > 0) {
                    for (MyAddress.DataBean bean : list) {
                        // 取默认地址 并且是在配送范围内
                        if (bean.getIs_default() == 1) {
                            rlAddress.setVisibility(View.GONE);
                            llAddress.setVisibility(View.VISIBLE);
                            tvName.setText("负责人：" + bean.getUname());
                            tvPhone.setText(bean.getMobile());
                            String street = bean.getStreet();
                            warehouse_id = bean.getAddress_id();
                            tvAddressDetails.setText("仓库地址：" + bean.getAddress_str() + " " + street);
                        } else {

                        }
                    }
                }
            } else {
                T.showToast(mContext, model.getMsg());
            }
        }
    }

    @Override
    public void getHomeClassSuccess(ClassModel model) {
        if (model != null) {
            if (model.getStatus() == HttpUtil.RESULT_OK) {
                data = model.getData();
                gc = data.getDomestic();
                jk = data.getImportX();
                if (data_type == 0) {
                    // 国产
                    classList = data.getDomestic();//国产
                } else if (data_type == 1) {
                    // 进口
                    classList = data.getImportX();// 进口
                }
                if (!isLoading) {
                    if (classList != null && classList.size() > 0) {
                        showClassDialog(classList);
                    }
                }
            }
        }
    }

    @Override
    public void getBasicSuccess(GetBasic model) {
        if (model != null) {
            if (model.getStatus() == HttpUtil.RESULT_OK) {
                GetBasic.DataBean data = model.getData();
                String no = data.getNo();
                String goods_name = data.getGoods_name();
                String country_name = data.getCountry_name();
                String specifications = data.getSpecifications();//规格
                String num = data.getNum();//量
                String packageX = data.getPackageX();//包装
                String weight = data.getWeight();//重量
                String volume = data.getVolume();//体积
                String single_specifications = data.getSingle_specifications();
                String single_num = data.getSingle_num();
                et_number.setText(num + "");
                et_discount.setText(specifications);
                tv_unit.setText(packageX);
                et_kg.setText(weight);
                et_volume.setText(volume);
                et_singe_num.setText(single_num);
                et_single_unit.setText(single_specifications);
                country_id = data.getCountry_id() + "";
                class_id = data.getClass_id() + "";
                int free_post = data.getIs_free_post();//是否包邮1不包2包 (不包要传use_ydx，包传free_post_num)
                String free_post_num = data.getFree_post_num();
                switch (free_post) {
                    case 1:
                        is_free_post = "1";
                        rbWithout.setChecked(true);
                        tvTransportLine.setVisibility(View.VISIBLE);
                        llTransport.setVisibility(View.VISIBLE);
                        ll_free_post_num.setVisibility(View.GONE);
                        tv_free_post_num.setVisibility(View.GONE);
                        break;
                    case 2:
                        is_free_post = "2";
                        rbFree.setChecked(true);
                        tvTransportLine.setVisibility(View.GONE);
                        llTransport.setVisibility(View.GONE);
                        ll_free_post_num.setVisibility(View.VISIBLE);
                        tv_free_post_num.setVisibility(View.VISIBLE);
                        et_mail.setText(free_post_num);
                        break;
                }
                String ydx_str = data.getUse_ydx();//使用运东西，1不使用2使用
                int ydx = 2;
                if (!Tools.isNull(ydx_str)) {
                    ydx = Integer.parseInt(ydx_str);
                }
                switch (ydx) {
                    case 1:
                        rbTransport2.setChecked(true);
                        use_ydx = "1";
                        break;
                    case 2:
                        rbTransport1.setChecked(true);
                        use_ydx = "2";
                        break;
                }

                etShopNumber.setText(no);
                etShopName.setText(goods_name);
                tv_field.setText(country_name);
                tv_classification.setText(data.getClass_name());
                etStarting.setText(data.getSold_least_num() + "");
                etRetailPrice.setText(data.getMarket_price());
                GetBasic.DataBean.WarehouseBean bean = data.getWarehouse();
                if (bean != null) {
                    rlAddress.setVisibility(View.GONE);
                    llAddress.setVisibility(View.VISIBLE);
                    tvName.setText("负责人：" + bean.getUname());
                    tvPhone.setText(bean.getMobile());
                    String street = bean.getStreet();
                    warehouse_id = bean.getAddress_id() + "";
                    tvAddressDetails.setText("仓库地址：" + bean.getAddress_str() + " " + street);
                }

                thumbs = data.getThumbs();
                photoInfos.clear();
                for (GetBasic.DataBean.ThumbsBean item : thumbs) {
                    LocalMedia info = new LocalMedia();
                    if (item.getPath().startsWith("http")) {
                        info.setPath(item.getPath());
                    } else {
                        info.setPath(item.getBase_url() + "/" + item.getPath());
                    }
                    photoInfos.add(info);
                }
                adapter.setPhotoInfos(photoInfos);
                adapter.notifyDataSetChanged();

                List<GetBasic.DataBean.DiscountBean> discount = data.getDiscount();
                for (GetBasic.DataBean.DiscountBean item : discount) {
                    Discount dis = new Discount();
                    dis.setCount(item.getCount() + "");
                    dis.setDiscount(item.getDiscount() + "");
                    discounts.add(dis);
                }
                discountAdapter.setList(discounts);
                discountAdapter.notifyDataSetChanged();

            } else {
                T.showToast(mContext, model.getMsg());
            }
        }
    }

    @Override
    public void editBasicInfoSuccess(Goods1Model model) {
        if (model != null) {
            if (model.getStatus() == HttpUtil.RESULT_OK) {
                setResult(RESULT_OK);
                finish();
            }
        }
    }

    @Override
    public void shoperDelImgSuccess(Collect model) {
        if (model != null) {
            if (model.getStatus() == HttpUtil.RESULT_OK) {
                Log.i("delete image status：", model.getMsg());
            }
        }
    }

    @Override
    public void ShoperInfoSuccess(ShoperModel model) {
        if (model != null) {
            if (model.getStatus() == HttpUtil.RESULT_OK) {
                ShoperModel.DataBean data = model.getData();
                if (data != null) {
                    product_type = data.getProduct_type();
                    // 保存商家商品类型
                    User user = (User) App.getInstance().readObject(HttpUtil.USER_KEY);
                    user.setProduct_type(product_type);
                    App.getInstance().saveObject(user, HttpUtil.USER_KEY);
                    Log.i("商品类型---------<", user.getProduct_type() + "");
                }
            }
        }
    }

    @Override
    public void httpStatusError() {

    }

    @Override
    public void hideLoading() {
        if (showType != 1) {
            hideShowProgress();
        }
    }

    @Override
    public void upProgress(long currentSize, long totalSize, float progress, long networkSpeed) {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (receiver != null) {
            unregisterReceiver(receiver);
        }
    }
}
